$(function () {

    let fall_list = $(".fall_list")
    let height_list

    function init() {
        load()
            .done(function (res) {
                render(res.mainlist3)
                sort()
                $(".lazy").lazyload();
            })

    }

    function load() {
        let options = {
            url: "../../static/libs/json/prototype.json",
            type : "GET",
            dataType : "json"
        }

        return $.ajax(options)

    }

    function render(list){
        fall_list.append( list.map( item => 
        `
            <div class="box"><img class="lazy"  src=${item.img}></div>
        `
        ).join(""))
    }

    function sort(){

        let $box = $(".box")
        height_list = []
        let offset_list = []
        
        $.each( $box , function(index , ele){

            if(index < 4){

                height_list.push( $(ele).outerHeight())
                offset_list.push( $(ele).position().left)
            
            }else{

                let min_height = Math.min.apply(false , height_list)
                let min_index = height_list.indexOf(min_height)
                let _left = offset_list[min_index]

                $(ele).css({

                    position : "absolute",
                    top : min_height,
                    left : _left

                })

                height_list[min_index] += $(ele).outerHeight()

            }

        })

    }

    //无限加载
    $(window).scroll(function(){
        //获取当前滚动高度
        let scrollTop = $("html,.body").scrollTop()
        let min_height = parseInt( Math.min.apply(false, height_list))
        //判断是否再次加载
        if(scrollTop + innerHeight  > min_height + 2500){
            console.log("加载图片");
            load()
            .done(function (res) {
                render(res.mainlist3)
                sort()
                $(".lazy").lazyload();
            })
        }
    })
    init()
})